/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package managedbean.Workspace;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import merlion.common.entity.Announcement;
import merlion.common.entity.SecurityRole;
import merlion.common.session.stateless.AnnouncementSessionLocal;
import merlion.common.session.stateless.SystemUserSessionBeanLocal;
import merlion.common.util.Consts;

/**
 *
 * @author Zhang Ying
 */
@ManagedBean
@ViewScoped
public class AnnouceManagerBean {

    @EJB
    private AnnouncementSessionLocal announceManager;
    @EJB
    private SystemUserSessionBeanLocal roleManager;
    @ManagedProperty(value = "#{workspaceManagerBean}")
    private WorkspaceManagerBean workspaceManagerBean;
    // attributes for creation of new announcements
    private Announcement newAnnouncement;
    private Collection<SecurityRole> allRoles;
    private SecurityRole[] selectedRoles;
    // attributes for manage announcements posted by me
    private Collection<Announcement> myMgedAnnouncements;
    private Announcement[] selectedDeletion;
    private Announcement selectedAnnouncement;
    private SecurityRole[] selectedAnnRoles;
    // attributes for normal people viewing announcements for them
    private Collection<Announcement> myAnnouncements;

    /** Creates a new instance of AnnouceManagerBean */
    public AnnouceManagerBean() {
        // initial new announcemnet and assign to current staff
        newAnnouncement = new Announcement();
    }

    // methods for new announcements
    public String postNew() {
        if (selectedRoles.length == 0) {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, "You should at least choose one security role.", "You should at least choose one security role."));
            return null;
        }
        // set audience and posterid for new announcemnt
        newAnnouncement.getAudience().addAll(Arrays.asList(selectedRoles));
        newAnnouncement.setPosterId(workspaceManagerBean.getCurrentStaff().getId());
        // persist it to database
        announceManager.addNewAnnouncement(newAnnouncement);
        return redirectToManagePage();
    }

    // for manage page
    public String viewOneAnnouncement(Long id) {
        return redirectToOneView() + "&annId=" + id;
    }

    public String selectAnnouncement(Long id) {
        setSelectedAnnouncement(announceManager.getAnnouncement(id));
        return null;
    }

    public String deleteOneAnnouncement() {
        if (selectedAnnouncement == null) {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, "Deletion Failed(no selected ann)", "Deletion Failed"));
            return null;
        }
        if (announceManager.deleteAnnouncement(selectedAnnouncement.getId())) {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_INFO, "Deletion Successful.", "Deletion Successful."));
            return null;
        } else {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, "Deletion Failed", "Deletion Failed"));
            return null;
        }
    }

    public String editOneAnnouncement(Long id) {
        return redirectToOneEdit() + "&annId=" + id;
    }

    public String deleteManyAnnouncements() {
        if (selectedDeletion.length == 0) {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, "You should at least choose one announcement to delete.", "You should at least choose one announcement to delete."));
            return null;
        }
        if (announceManager.deleteManyAnnouncements(selectedDeletion)) {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_INFO, "Deletion Successful.", "Deletion Successful."));
            return null;
        } else {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, "Deletion Failed", "Deletion Failed"));
            return null;
        }
    }

    // manage one view
    public String editOneFromView() {
        return redirectToOneEdit() + "&annId=" + selectedAnnouncement.getId();
    }

    // manage one edit
    public String saveEdition() {
        if (selectedAnnRoles.length == 0) {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, "You should at least choose one security role.", "You should at least choose one security role."));
            return null;
        }
        // save to selectedAnnouncement
        Collection<SecurityRole> srs = new ArrayList<SecurityRole>();
        srs.addAll(Arrays.asList(selectedAnnRoles));
        selectedAnnouncement.setAudience(srs);
        // persist it
        if (announceManager.updateAnnouncement(selectedAnnouncement)) {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_INFO, "Update Successful.", "Update Successful."));
        } else {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, "Update Failed", "Update Failed"));
            return null;
        }
        return redirectToManagePage();
    }

    public String deleteCurrentOne() {
        if (announceManager.deleteAnnouncement(selectedAnnouncement.getId())) {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_INFO, "Deletion Successful.", "Deletion Successful."));
        } else {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, "Deletion Failed", "Deletion Failed"));
            return null;
        }
        return redirectToManagePage();
    }
    
    // for view anns
    public String viewOneMyAnn(Long id){
        return redirectToMyOneView()+ "&annId=" + id; 
    }

    // setters and getters
    // for creation
    public Announcement getNewAnnouncement() {
        return newAnnouncement;
    }

    public void setNewAnnouncement(Announcement newAnnouncement) {
        this.newAnnouncement = newAnnouncement;
    }

    public Collection<SecurityRole> getAllRoles() {
        allRoles = roleManager.getAllSecurityRoles();
        return allRoles;
    }

    public void setAllRoles(Collection<SecurityRole> allRoles) {
        this.allRoles = allRoles;
    }

    public WorkspaceManagerBean getWorkspaceManagerBean() {
        return workspaceManagerBean;
    }

    public void setWorkspaceManagerBean(WorkspaceManagerBean workspaceManagerBean) {
        this.workspaceManagerBean = workspaceManagerBean;
    }

    public SecurityRole[] getSelectedRoles() {
        return selectedRoles;
    }

    public void setSelectedRoles(SecurityRole[] selectedRoles) {
        this.selectedRoles = selectedRoles;
    }

    // for manage
    public Collection<Announcement> getMyMgedAnnouncements() {
        myMgedAnnouncements = announceManager.getAllMyMgedAnnouncements(workspaceManagerBean.getCurrentStaff().getId());
        return myMgedAnnouncements;
    }

    public void setMyMgedAnnouncements(Collection<Announcement> myMgedAnnouncements) {
        this.myMgedAnnouncements = myMgedAnnouncements;
    }

    public Announcement[] getSelectedDeletion() {
        return selectedDeletion;
    }

    public void setSelectedDeletion(Announcement[] selectedDeletion) {
        this.selectedDeletion = selectedDeletion;
    }

    public Announcement getSelectedAnnouncement() {
        if (selectedAnnouncement == null) {
            HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
            String parameter = request.getParameter("annId");
            if (parameter != null) {
                Long id = Long.valueOf(parameter);
                selectedAnnouncement = announceManager.getAnnouncement(id);
            }
        }
        return selectedAnnouncement;
    }

    public void setSelectedAnnouncement(Announcement selectedAnnouncement) {
        this.selectedAnnouncement = selectedAnnouncement;
    }

    public SecurityRole[] getSelectedAnnRoles() {
        if (selectedAnnouncement != null) {
            int i = 0;
            Collection<SecurityRole> aud = selectedAnnouncement.getAudience();
            selectedAnnRoles = new SecurityRole[aud.size()];
            for (SecurityRole sr : aud) {
                selectedAnnRoles[i] = sr;
                i++;
            }
        }
        return selectedAnnRoles;
    }

    public void setSelectedAnnRoles(SecurityRole[] selectedAnnRoles) {
        this.selectedAnnRoles = selectedAnnRoles;
    }
    
    // for view anns

    public Collection<Announcement> getMyAnnouncements() {
        myAnnouncements = announceManager.getAllMyAnnouncements(workspaceManagerBean.getCurrentStaff());
        return myAnnouncements;
    }

    public void setMyAnnouncements(Collection<Announcement> myAnnouncements) {
        this.myAnnouncements = myAnnouncements;
    }
    
    public String getPosterFullName(Long id){
        return announceManager.getPoster(id).getFullName();
    }

    public String getSelectedAnnPosterName(){
        return announceManager.getPoster(selectedAnnouncement.getPosterId()).getFullName();
    }
    // navigation methods
    private String getRedirectPath(String path) {
        return path + "?faces-redirect=true";
    }

    public String redirectToPostNewPage() {
        return getRedirectPath(Consts.ANNOUCEMENT_CREATE_PATH);
    }

    public String redirectToManagePage() {
        return getRedirectPath(Consts.ANNOUCEMENT_MANAGE_PATH);
    }

    public String redirectToOneEdit() {
        return getRedirectPath(Consts.ANNOUCEMENT_MANAGE_PATH + "OneEdit");
    }

    public String redirectToOneView() {
        return getRedirectPath(Consts.ANNOUCEMENT_MANAGE_PATH + "OneView");
    }
    
    public String redirectToMyOneView(){
        return getRedirectPath(Consts.VIEW_MY_ANNS+"One");
    }
    
    // for home page
    
    public Collection<Announcement> getRecentAtMostFiveAnns(Long accId){
        return announceManager.getRecentAtMostFiveAnns(accId);
    }
}
